
import { useEffect, useState } from 'react'
import Taro, { FC } from '@tarojs/taro'
import { AtInput, AtForm, AtIcon, AtList, AtListItem } from "taro-ui"
import { debounceTime, switchMap } from 'rxjs/operators';
import { Subscription, Subject } from 'rxjs';
import "taro-ui/dist/style/components/image-picker.scss";
import { View, Text, Image } from '@tarojs/components'
import "taro-ui/dist/style/components/button.scss" // 按需引入 
import { uploadFile } from '@/utils/qcloudHelpers';
import { onEmit } from '@/utils/rxHelpers';
import { useAuthFacade } from '@/hooks/useAuthFacade';
import { ApprovalStatus } from '@/models/request/userReq';
import { getLogger } from '@/utils/log';
import { rsgOrgNum } from '@/utils/regexRule';

import ChannelStyle from '@@/channel/channelStyle'
import './index.scss'

//机构认证
export const OrgVerify: FC = () => {
  const logger = getLogger("/pages/my/orgVerify");

  //用不到的变量不用写
  const [authFacade, , , , orgs] = useAuthFacade();

  const initSubject = () => new Subject<any>();
  const [emitter, setEmitter] = useState<Subject<any>>(initSubject)

  const [inputOrgName, setInputOrgName] = useState("")
  const [inputOrgNo, setInputOrgNo] = useState('')
  const [orgImg, setOrgImg] = useState("")

  // 初始化赋值
  useEffect(() => {
    if (orgs.length > 0) {
      setInputOrgName(orgs[0].orgName)
      setInputOrgNo(orgs[0].orgNo)
    }

  }, [orgs]);
  //把按钮点击事件转化为observable
  const orgApprove$ = emitter.asObservable()
    .pipe(
      //防抖动(防重复)
      debounceTime(400),
      //接收按钮点击的参数
      switchMap((orgApproveObj) => {
        console.log("orgApproveObj:", orgApproveObj)
        if (!orgApproveObj.orgName) {
          throw Taro.showToast({
            title: '请输入机构名称',
            icon: 'none',
            duration: 2000
          })
        }
        // 校验机构名称
        rsgOrgNum(orgApproveObj.orgNo)
        if (!orgApproveObj.orgNo) {
          throw Taro.showToast({
            title: '请输入机构代码',
            icon: 'none',
            duration: 2000
          })
        }
        if (!orgApproveObj.orgImg) {
          throw Taro.showToast({
            title: '请上传营业执照',
            icon: 'none',
            duration: 2000
          })

        }
        Taro.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 2000
        })
        return authFacade.orgApprove(orgApproveObj)

      })
    )

  const handleChangeOrgName = (value: string) => {
    setInputOrgName(value)
  }
  const handleChangeOrgNo = (value: string) => {
    setInputOrgNo(value)
  }
  //校验社会信用码
  const handleCheckRule = (value: string) => {
    rsgOrgNum(value)
  }

  // 删除图片
  const handleDelImg = () => {
    setOrgImg("")

  }
  //返回上一层
  const goBack = () => {
    Taro.showToast({
      title: '保存成功',
      icon: 'none',
      duration: 2000
    }).then(() => {
      setTimeout(() => {
        Taro.navigateBack({
          delta: 1
        })
      }, 1000)
    })
  }

  // 上传图片
  const pickImage = (pos: string) => {
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function (res) {
        uploadFile(res.tempFilePaths[0],
          (resUrl: string) => {
            //Fixme， 上传完成之前，都不允许点击保存按钮，否则请求后端的图片参数为空 
            setOrgImg(resUrl);
          }
        )
      }
    })
  }

  //FIXME 这里有执行两次的问题，是Taro的bug。等同于Component的componentWillMount
  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      onEmit<ApprovalStatus>(
        orgApprove$,
        res => {
          goBack();
          console.log("本地auth store快照1: ",)
        },
        err => {
          logger.ERROR("保存信息失败！", err);
          setEmitter(initSubject);
        }
      ),
    ]
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [orgApprove$]);

  return (
    <View className='index'>
      <View className='main'>
        <View>
          <AtList>
            <AtListItem title='信息提交' className='top-title' />
          </AtList>
          <AtForm>
            <AtInput
              name='value1'
              title='机构名称'
              type='text'
              placeholder=''
              value={inputOrgName}
              onChange={handleChangeOrgName.bind(this)}
              className='text'
            >
              <AtIcon value='chevron-right' size='20' color='#ccc'></AtIcon>
            </AtInput>
            <AtInput
              name='value2'
              title='统一社会信用代码'
              type='text'
              placeholder=''
              value={inputOrgNo}
              onChange={handleChangeOrgNo.bind(this)}
              onBlur={handleCheckRule.bind(this)}
              className='text'
            >
              <AtIcon value='chevron-right' size='20' color='#ccc'></AtIcon>
            </AtInput>
            <View className='title'>
              <Text className='push'>上传证明信息</Text>
            </View>
            <View className='upload-img'>
              <Image src={orgImg} className='pick1' onClick={() => pickImage("orgImg")}></Image>
              <View>
                {orgImg && orgImg.length > 0 && (<View className='icon-del' onClick={handleDelImg}></View>)}
                {!orgImg && <Text className='text1'>上传执照</Text>}
              </View>
            </View>

          </AtForm>
        </View>
        {/* 说明信息 */}
        <View className='tips-msg'>
          <Text>说明：{ChannelStyle.appName}LIVE承诺认证信息严格保密，未做授权，不将信息另做他用，请放心认证。</Text>
        </View>

        <View className='bt' onClick={e => emitter.next({
          orgName: inputOrgName,
          orgNo: inputOrgNo,
          orgImg,
        })}
        >
          <Text>提交认证</Text>
        </View>
      </View>
    </View>
  )
}
export default OrgVerify


